#!/usr/bin/env python3
# coding:utf-8

import socket
import time
from pylsl import StreamInlet, resolve_stream

moveFlag = 0.2
fastFlag = 0.3
massage_stop = None
massage_move = "6"
massage_fast = "5"

def init_socket_connection(ip, port):
    robot_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    robot_socket.connect((ip, port))

    return robot_socket

###### 命令对应动作部分由用户自定义 ######
CMD_MAP = {
    "1": "Squat",
    "2": "Left_hand_up",
    "3": "Right_hand_up",
    "4": "Single_leg_stand",
    "5": "向前快走3步",
    "6": "向前慢走3步"
}

#这个函数用不到
def show_command(val):
    print("Command List:")
    print("1.下蹲")
    print("2.举左手")
    print("3.举右手")
    print("4.金鸡独立")
    print("5.向前快走3步")
    print("6.向前慢走3步")
    val = input("请输入动作选项: ")


    if val in CMD_MAP.keys():
        return CMD_MAP.get(val)
    else:
        return None

def get_cmd(sample):
    if sample != -1:
        if sample <= moveFlag:
            return None
        elif sample <= fastFlag:
            return CMD_MAP.get(massage_move).encode()
        else:
            return CMD_MAP.get(massage_fast).encode()
    else:
        return None

if __name__ == '__main__':
    server_ip = '192.168.31.67'
    server_port = 10000
    robot_socket = init_socket_connection(server_ip, server_port)

    # first resolve an EEG stream on the lab network
    print("looking for a stream...")
    streams = resolve_stream('type', 'Performance-Metrics')
    print(streams)

    # create a new inlet to read from the stream
    inlet = StreamInlet(streams[0])

    # print(robot_socket.recv(1024).decode())
    # robot_socket.close()
    while True:
        sample, timestamp = inlet.pull_sample()
        print(timestamp, sample)
        time.sleep(0.5)
        #sample数据：[time?,Engagement,Excitement,Focus,Interest,Relaxation,Stress]

        #val = show_command()
        massage = get_cmd(sample[3])
        
        if massage != None:
            #pass
            robot_socket.send(massage)
            #print("执行动作 %s \n\n" %(massage.decode()))
        else:
            pass
            #print("无效的输入值\n\n")